package com.yishe.biz.wx.common;

import com.yishe.api.RestCodeConstants;
import com.yishe.biz.mysql.WxUserBiz;
import com.yishe.biz.mysql.WxUserMemberInfoBiz;
import com.yishe.config.ObjectRestResponse;
import com.yishe.constant.WxConstants;
import com.yishe.entites.mysql.WxUser;
import com.yishe.entites.mysql.WxUserMemberInfo;
import com.yishe.mapper.mysql.WxUserMemberInfoMapper;
import com.yishe.utils.CommonUtils;
import com.yishe.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author : chusifeng
 * @version :
 * @date :Create in 2021/4/14 14:37
 * @description: 微信用户系统工具
 * @package com.yishe.biz.wx.common
 * @className WxCommonBiz
 */
@Service
@Slf4j
public class WxCommonBiz {
    @Resource
    private WxUserBiz wxUserBiz;
    @Resource
    private WxUserMemberInfoBiz wxUserMemberInfoBiz;
    @Resource
    private WxMpService wxMpService;
    @Value("${wx.img.downloadUlr}")
    private String downloadUlr;
    @Value("${wx_img_path}")
    private String imgPath;
    @Resource
    private RestTemplate restProxyTemplate;
    /**
     * 根据传入的手机号检测
     * @param param
     * @return
     */
    public String checkPhone(Map<String, String> param) {
        String phone = param.get("phone");
        if (StringUtils.isBlank(phone)) {
            return "改手机号未被注册";
        }
        WxUser wxUser = new WxUser();
        wxUser.setTelePhone(phone);
        List<WxUser> list =  wxUserBiz.selectList(wxUser);
        if (CollectionUtils.isNotEmpty(list)) {
            return WxConstants.PHONEERROR;
        }
        return WxConstants.EMPTY;
    }

    /**
     * 注册
     * @param param
     * @return
     */
    @Transactional(value = "mysqlTransactionManager", rollbackFor = Exception.class)
    public String register(Map<String, String> param) {
        String phone = param.get("tele_phone");
        //校验手机号
        WxUser newUser = new WxUser();
        newUser.setTelePhone(phone);
        List<WxUser> ls = wxUserBiz.selectList(newUser);
        if (CollectionUtils.isNotEmpty(ls)){
            return WxConstants.PHONEERROR;
        }
        String nickname = param.get("nickname");
        String password = param.get("password");
        newUser.setPassword(password);
        newUser.setNickname(nickname);
        newUser.setWxAccount(CommonUtils.createWxAccount());
        wxUserBiz.insert(newUser);

        WxUserMemberInfo wxUserMemberInfo = new WxUserMemberInfo();
        wxUserMemberInfo.setWxAccount(newUser.getWxAccount());
        wxUserMemberInfo.setJfCurrent(0);
        wxUserMemberInfo.setJfTotal(0);
        wxUserMemberInfo.setJfUsed(0);
        wxUserMemberInfo.setMemberCurLevel("1");
        wxUserMemberInfo.setMemberGetTime(new Date());
        wxUserMemberInfo.setMoneyRefund(0.0D);
        wxUserMemberInfo.setMoneySurplus(0.0D);
        wxUserMemberInfo.setMoneyTotal(0.0D);
        wxUserMemberInfo.setJfCurrent(0);
        wxUserMemberInfoBiz.insert(wxUserMemberInfo);
        return WxConstants.EMPTY;
    }

    /**
     * 根据
     * @param medical_id
     * @param fileName
     * @return
     * @throws WxErrorException
     * @throws FileNotFoundException
     */
    public String downloadImgFronWx(String medical_id) throws WxErrorException, FileNotFoundException {
        String access_token = wxMpService.getAccessToken();
        String url = downloadUlr+"?access_token="+access_token+"&media_id="+medical_id;
        HttpUtils.setRestTemplateProxy(restProxyTemplate);
        ObjectRestResponse imgRes = HttpUtils.httpGetImg(url);
        String flag="error";
        if (imgRes.getResultCode() == RestCodeConstants.RESULT_SUCCESS) {
            String fileName  =medical_id+".jpg";
            File file = new File(imgPath+File.separator+fileName);
            byte[] fileBytes = (byte[]) imgRes.getData();
            FileOutputStream fos = new FileOutputStream(file);
            try (BufferedOutputStream bas = new BufferedOutputStream(fos)){
                bas.write(fileBytes);
                flag = fileName;
            } catch (IOException e) {
                log.error("从微信服务器下载图片失败！",e);

            }
        }
        return flag;
    }
}
